package com.bsoft.gol.hbs.service.impl;

import com.bsoft.gol.hbs.bean.Vo.HealthInfoReplyBaseVO;
import com.bsoft.gol.hbs.bean.dto.HealthInfoInteractionCountUpdateDTO;
import com.bsoft.gol.hbs.bean.enums.ArticleStatusEnum;
import com.bsoft.gol.hbs.bean.exception.ServiceException;
import com.bsoft.gol.hbs.bean.qo.HealthInfoCommentDashboardQo;
import com.bsoft.gol.hbs.bean.qo.HealthInfoReplyListQo;
import com.bsoft.gol.hbs.bean.qo.MyArticleListQo;
import com.bsoft.gol.hbs.bean.qo.NewReplyListQo;
import com.bsoft.gol.hbs.dao.HealthInfoDAO;
import com.bsoft.gol.hbs.dao.HealthInfoReplyDAO;
import com.bsoft.gol.hbs.dao.PcnTagsDAO;
import com.bsoft.gol.hbs.healthinfo.HealthInfoHandler;
import com.bsoft.gol.hbs.message.sendMsg.SendInteractionServiceImpl;
import com.bsoft.gol.hbs.utils.BeanUtils;
import com.bsoft.gol.hbs.utils.CommonUtils;
import com.bsoft.gol.hbs.utils.DateUtils;
import ctd.account.UserRoleToken;
import ctd.controller.exception.ControllerException;
import ctd.dictionary.Dictionary;
import ctd.dictionary.DictionaryItem;
import ctd.dictionary.controller.DictionaryController;
import ctd.mvc.upload.FileMetaEntity;
import ctd.mvc.upload.FileService;
import ctd.mvc.upload.exception.FileRegistryException;
import ctd.net.rpc.Client;
import ctd.persistence.annotation.DAOTransaction;
import ctd.spring.boot.annotation.SsdevService;
import ctd.util.annotation.RpcService;
import hcn.base.BaseActionRecord;
import hcn.base.DocIdentity;
import hcn.base.Doctor;
import hcn.base.healthinfo.HealthInfo;
import hcn.base.healthinfo.HealthInfoReply;
import hcn.base.healthinfo.HealthInfoService;
import hcn.base.healthinfo.qo.*;
import hcn.base.healthinfo.vo.*;
import hcn.bean.UserVo;
import hcn.enums.UserRoleEnum;
import hcn.rep.request.DiseaseSpeciesSimpleListReq;
import hcn.rep.response.DiseaseSpeciesSimpleListRep;
import lombok.extern.slf4j.Slf4j;
import org.atag.dao.model.PageInfo;
import org.atag.dao.model.PageQo;
import org.atag.dao.model.SimplePageInfo;
import org.atag.util.bbp.RoleUtils;
import org.atag.util.common.RpcUtil;
import org.springframework.beans.factory.annotation.Autowired;
import pcn.bean.FindPatientLeaveMessageVo;
import pcn.bean.chissign.ChisQuerySignQo;
import pcn.bean.consultation.FindPatientLeaveMessageQo;
import pcn.enums.BusinessTypeEnum;
import pcn.enums.CmsActionEnum;
import pcn.enums.RoleIdEnum;
import pcn.sign.DoctInfo;
import pcn.sign.PcnSignPersonGroup;
import pcn.vo.chissign.ChisSignVO;
import service.rpc.BaseUserManageUnitIntf;
import service.rpc.DocIdentityRpcService;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;


/**
 * 健康资讯
 *
 * @author linyi
 * @date 2021/10/8 14:17
 */
@Slf4j
@SsdevService("healthNews")
public class HealthInfoServiceImpl implements HealthInfoService {


    @Autowired
    private HealthInfoDAO healthInfoDAO;

    @Autowired
    private HealthInfoReplyDAO healthInfoReplyDAO;

    @Autowired
    private BaseActionRecordService baseActionRecordService;

    @Autowired
    private BaseUserManageUnitIntf baseUserManageUnitService;
    @Autowired
    private PcnTagsDAO pcnTagsDAO;

    @Autowired
    private SendInteractionServiceImpl sendInteractionService;
    @Autowired
    private DocIdentityRpcService docIdentityRpcService;
    @Autowired
    private HealthInfoService healthInfoService;

    private List<FileMetaEntity> getUserFileList(List<String> fileIds) {
        if (CommonUtils.isNotEmpty(fileIds)) {
            return fileIds.stream().map(id -> {
                try {
                    return FileService.instance().load(id);
                } catch (FileRegistryException e) {
                    log.error("获取文件信息失败,{}", id);
                }
                return null;
            }).filter(CommonUtils::isNotEmpty).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    @RpcService
    public long getCountByDoctorId(String doctorId) {
        return healthInfoDAO.getCountByDoctorId(doctorId);
    }

    /**
     * 健康资讯文章列表
     */
    @Override
    public SimplePageInfo<MyArticleListVO> myArticleList(MyArticleListRequest request) {
        //医生视图
        request.setUserId(UserRoleToken.getCurrent().getUserId());

        SimplePageInfo<HealthInfo> healthInfoList = healthInfoDAO.getHealthInfoPage(copyArticleListQo(request));
        return alterArticleList(healthInfoList);
    }

    /**
     * 健康资讯审核列表
     */
    @Override
    public SimplePageInfo<MyArticleListVO> auditArticleList(MyArticleListRequest request) {
        MyArticleListQo qo = copyArticleListQo(request);
        qo.setUserId(null);
        qo.setArticleStatusList(Arrays.asList(ArticleStatusEnum.SUBMITTED.getState(), ArticleStatusEnum.RELEASED.getState()));
        qo.setDesc(true);
        SimplePageInfo<HealthInfo> healthInfoList = healthInfoDAO.getHealthInfoPage(qo);
        return alterArticleList(healthInfoList);
    }

    private SimplePageInfo<MyArticleListVO> alterArticleList(SimplePageInfo<HealthInfo> healthInfoList) {

        SimplePageInfo<MyArticleListVO> pageInfo = new SimplePageInfo<>();
        pageInfo.setTotal(healthInfoList.getTotal());
        if (CommonUtils.isNotEmpty(healthInfoList) && CommonUtils.isNotEmpty(healthInfoList.getList())) {
            List<MyArticleListVO> collect = healthInfoList.getList().stream()
                    .map(info -> BeanUtils.copyProperties(info, MyArticleListVO.class))
                    .collect(Collectors.toList());
            pageInfo.setList(collect);
        } else {
            pageInfo.setList(Collections.emptyList());
        }
        return pageInfo;
    }

    @Override
    public SimplePageInfo<MyArticleListVO> articleList(ArticleListRequest request) {
        String roleId = RoleUtils.getCurrentCommonRole();
        MyArticleListQo qo = copyArticleListQo(request);
        if (CommonUtils.isEmpty(qo)) {
            return new SimplePageInfo<>();
        }
        qo.setArticleStatus(ArticleStatusEnum.RELEASED.getState());
        qo.setDesc(true);
        SimplePageInfo<HealthInfo> healthInfoList;
        Integer category = request.getCategory();
        String mpiId = request.getMpiId();
        //只有选择了就诊人的时候才显示推荐列表
        if (RoleIdEnum.PATIENT.title().equals(roleId) && CommonUtils.isNotEmpty(mpiId) &&
                CommonUtils.isNotEmpty(category) && category.equals(Constant.RECOMMEND_TYPE)) {
            //患者端推荐功能
            //入组疾病
            //根据mpiId 查询对应的入组记录
            List<String> diseaseIds = findChronicDiseaseIdByPersonId(mpiId);
            qo.setDiseaseGroup(diseaseIds);
            try {
                //家医签约
                //根据mpiId获取家医签约信息
                List<String> groupList = getPersonGroupFromPhis(mpiId);
                qo.setPersonGroup(groupList);
            } catch (Exception e) {
                log.error("查询家医签约信息异常", e);
            }
            healthInfoList = healthInfoDAO.getRecommendHealthInfoList(qo);
        } else {
            if (CommonUtils.isNotEmpty(category) && category.equals(Constant.RECOMMEND_TYPE)) {
                qo.setCategory(null);
            }
            healthInfoList = healthInfoDAO.getHealthInfoPage(qo);
        }
        //医生端无推荐
        SimplePageInfo<MyArticleListVO> pageInfo = alterArticleList(healthInfoList);
        List<MyArticleListVO> list = pageInfo.getList();
        //  查询是否有新的留言
        if (CommonUtils.isNotEmpty(list) && !RoleIdEnum.PATIENT.title().equals(roleId)) {
            List<String> articleIds = list.stream().map(MyArticleListVO::getArticleId).collect(Collectors.toList());
            List<String> newReply = healthInfoReplyDAO.findNewReply(articleIds);
            if (CommonUtils.isNotEmpty(newReply)) {
                Map<String, Boolean> newReplyMap = newReply.stream().collect(Collectors.toMap(r -> r, r -> Boolean.TRUE));
                list.forEach(c -> c.setNewReply(newReplyMap.getOrDefault(c.getArticleId(), Boolean.FALSE)));
            }
        }
        return pageInfo;
    }

    @Override
    public SimplePageInfo<MyArticleListVO> articleListLeaveMessage(ArticleListRequest request) {
        String roleId = RoleUtils.getCurrentCommonRole();
        MyArticleListQo qo = copyArticleListQo(request);
        if (CommonUtils.isEmpty(qo)) {
            return new SimplePageInfo<>();
        }
        qo.setArticleStatus(ArticleStatusEnum.RELEASED.getState());
        qo.setDesc(true);
        SimplePageInfo<HealthInfo> healthInfoList;
        Integer category = request.getCategory();
        String mpiId = request.getMpiId();
        //只有选择了就诊人的时候才显示推荐列表
        if (RoleIdEnum.PATIENT.title().equals(roleId) && CommonUtils.isNotEmpty(mpiId) &&
                CommonUtils.isNotEmpty(category) && category.equals(Constant.RECOMMEND_TYPE)) {
            //患者端推荐功能
            //入组疾病
            //根据mpiId 查询对应的入组记录
            List<String> diseaseIds = findChronicDiseaseIdByPersonId(mpiId);
            qo.setDiseaseGroup(diseaseIds);
            try {
                //家医签约
                //根据mpiId获取家医签约信息
                List<String> groupList = getPersonGroupFromPhis(mpiId);
                qo.setPersonGroup(groupList);
            } catch (Exception e) {
                log.error("查询家医签约信息异常", e);
            }
            healthInfoList = healthInfoDAO.getRecommendHealthInfoList(qo);
        } else {
            if (CommonUtils.isNotEmpty(category) && category.equals(Constant.RECOMMEND_TYPE)) {
                qo.setCategory(null);
            }
            healthInfoList = healthInfoDAO.getInfoListForWord(qo);
        }
        //医生端无推荐
        SimplePageInfo<MyArticleListVO> pageInfo = alterArticleList(healthInfoList);
        List<MyArticleListVO> list = pageInfo.getList();
        //  查询是否有新的留言
        if (CommonUtils.isNotEmpty(list) && !RoleIdEnum.PATIENT.title().equals(roleId)) {
            List<String> articleIds = list.stream().map(MyArticleListVO::getArticleId).collect(Collectors.toList());
            List<String> newReply = healthInfoReplyDAO.findNewReply(articleIds);
            if (CommonUtils.isNotEmpty(newReply)) {
                Map<String, Boolean> newReplyMap = newReply.stream().collect(Collectors.toMap(r -> r, r -> Boolean.TRUE));
                list.forEach(c -> c.setNewReply(newReplyMap.getOrDefault(c.getArticleId(), Boolean.FALSE)));
            }
        }
        return pageInfo;
    }

    private MyArticleListQo copyArticleListQo(Object request) {
        MyArticleListQo qo = new MyArticleListQo();
        org.springframework.beans.BeanUtils.copyProperties(request, qo);
        return qo;
    }

    private List<String> getPersonGroupFromPhis(String mpiId) {
        //根据mpiId获取身份证号
        String idCard = RpcUtil.invoke("pcn.mpiIdentityService", "getIdCardByMpiId", mpiId);
        if (CommonUtils.isEmpty(idCard)) {
            return Collections.emptyList();
        }
        ChisSignVO chisSignVO = new ChisSignVO();
        ChisQuerySignQo chisQuerySignQo = new ChisQuerySignQo();
        chisQuerySignQo.setPageNo(1);
        chisQuerySignQo.setPageSize(1);
        chisQuerySignQo.setIdCard(idCard);
        //SignEnum
        chisQuerySignQo.setSignFlag("13,43,51");
        try {
            PageInfo pageInfo = (PageInfo) Client.rpcInvoke("pcn.familySignService", "getSignRecordList", chisQuerySignQo);
            if (CommonUtils.isNotEmpty(pageInfo) && CommonUtils.isNotEmpty(pageInfo.getList())) {
                chisSignVO = (ChisSignVO) pageInfo.getList().get(0);
            }
        } catch (Throwable throwable) {
            log.error("获取公卫签约列表信息失败", throwable);
            throw new ServiceException("获取公卫签约信息失败");
        }
        String peopleFlag = chisSignVO.getPeopleFlag();
        if (CommonUtils.isEmpty(peopleFlag)) {
            return Collections.emptyList();
        }
        String[] split = peopleFlag.split(",");
        return Arrays.asList(split);
    }

    /**
     * 获取当前用户的家医人群分类
     *
     * @deprecated 本地目前木有保存对应的人群分类
     */
    @Deprecated
    private List<String> getGroupList(String userId) {
        try {
            //根据userId获取mpiId
            String mpiId = RpcUtil.invoke("pcn.mpiIdentityService", "getMpiIdByUserId", userId);
            return getGroupListByMpiId(mpiId);
        } catch (Exception e) {
            //do nothing
        }
        return Collections.emptyList();
    }

    /**
     * 根据mpiId获取家医人群分类
     *
     * @deprecated 本地目前木有保存对应的人群分类
     */
    @Deprecated
    private List<String> getGroupListByMpiId(String mpiId) {
        try {
            if (CommonUtils.isNotEmpty(mpiId)) {
                List<PcnSignPersonGroup> personGroups = RpcUtil.invoke("pcn.pcnSignPersonGroupService", "findPcnSignPersonGroupsByMpiId", mpiId);
                if (CommonUtils.isNotEmpty(personGroups)) {
                    //获取去重的家医人群分类代码
                    return personGroups.stream().filter(p -> CommonUtils.isNotEmpty(p.getGroupCode())).map(p -> {
                        String groupCode = p.getGroupCode();
                        return Stream.of(groupCode.split(",")).collect(Collectors.toList());
                    }).flatMap(Collection::stream).distinct().collect(Collectors.toList());
                }
            }
        } catch (Exception e) {
            //do nothing
        }
        return Collections.emptyList();
    }

    /**
     * 获取用户入组的慢病id列表
     */
    private List<String> findChronicDiseaseIdByPersonId(String mpiId) {
        try {
            List<Long> ids = RpcUtil.invoke("hcs.teamChronicGroup", "queryDiseaseIdByPersonId", mpiId);
            if (CommonUtils.isNotEmpty(ids)) {
                return ids.stream().map(Object::toString).collect(Collectors.toList());
            }
        } catch (Exception e) {
            //do nothing
        }
        return Collections.emptyList();
    }

    @Override
    public PersonGroupVO personGroup(String organizationId) {
        PersonGroupVO vo = new PersonGroupVO();
        if (CommonUtils.isNull(organizationId)) {
            //前端那边由于页面复用，会用空值调用该接口，已与前端约定，空值调用，直接返回空给前端
            return vo;
        }
        //获取家医人群分类
        try {
            Dictionary dictionary = DictionaryController.instance().get("hcn.health.dictionary.personGroup");
            List<DictionaryItem> dicList = dictionary.getSlice(null, 0, null);
            if (CommonUtils.isNotEmpty(dicList)) {
                List<PersonGroupVO.PersonGroup> personGroups = dicList.stream().map(dic -> {
                    PersonGroupVO.PersonGroup p = new PersonGroupVO.PersonGroup();
                    p.setPersonGroupId(dic.getKey());
                    p.setPersonGroupName(dic.getText());
                    return p;
                }).collect(Collectors.toList());
                vo.setPersonGroupList(personGroups);
            }
        } catch (ControllerException e) {
            throw new ServiceException(e.getMessage());
        }
        //rpc获取病种列表
        DiseaseSpeciesSimpleListReq req = new DiseaseSpeciesSimpleListReq();
        req.setOrganizationId(organizationId);
        List<DiseaseSpeciesSimpleListRep> result = RpcUtil.invoke("hcs.diseaseSpecies", "querySimpleDiseaseList", req);
        if (CommonUtils.isNotEmpty(result)) {
            List<PersonGroupVO.DiseaseSpecies> diseaseSpecies = result.stream().map(r -> {
                PersonGroupVO.DiseaseSpecies d = new PersonGroupVO.DiseaseSpecies();
                d.setDiseaseSpeciesId(String.valueOf(r.getDiseaseTypeId()));
                d.setDiseaseSpeciesName(r.getDiseaseTypeName());
                return d;
            }).collect(Collectors.toList());
            vo.setDiseaseSpeciesList(diseaseSpecies);
        }
        //获取孕期所属状态（字典）
        try {
            Dictionary dictionary = DictionaryController.instance().get("hcn.mch.dictionary.pregnancyStatus");
            List<DictionaryItem> dictionaryItemList = dictionary.getSlice(null, 0, null);
            if (CommonUtils.isNotEmpty(dictionaryItemList)) {
                List<PersonGroupVO.PregnancyStatus> pregnancyStatusList = dictionaryItemList.stream().map(dic -> {
                    PersonGroupVO.PregnancyStatus p = new PersonGroupVO.PregnancyStatus();
                    p.setPregnancyStatusId(dic.getKey());
                    p.setPregnancyStatusName(dic.getText());
                    return p;
                }).collect(Collectors.toList());
                vo.setPregnancyStatusList(
                        pregnancyStatusList);
            }
        } catch (ControllerException e) {
            e.printStackTrace();
            throw new ServiceException(e.getMessage());
        }
        return vo;
    }

    /**
     * 文章详情
     */
    @Override
    public MyArticleDetailVO articleDetail(String articleId) {
        HealthInfo healthInfo = healthInfoDAO.get(articleId);
        //   专科随访分类  家医健康分类
        if (CommonUtils.isNotEmpty(healthInfo)) {
            MyArticleDetailVO vo = BeanUtils.copyProperties(healthInfo, MyArticleDetailVO.class);
            if (Objects.isNull(vo)) {
                return null;
            }

            // 附件列表
            String fileList = healthInfo.getFileList();
            if (CommonUtils.isNotEmpty(fileList)) {
                List<FileMetaEntity> userFileList = getUserFileList(Arrays.asList(fileList.split(",")));
                if (CommonUtils.isNotEmpty(userFileList)) {
                    List<MyArticleDetailVO.File> collect = userFileList.stream().map(file -> {
                        MyArticleDetailVO.File f = new MyArticleDetailVO.File();
                        f.setFileId(file.getFileId());
                        f.setFileName(file.getFileName());
                        return f;
                    }).collect(Collectors.toList());
                    vo.setFileList(collect);
                }
            }
            //人群分类列表
            List<MyArticleDetailVO.Item> pList = contactGroupList(healthInfo.getPersonGroupList(), healthInfo.getPersonGroupName());
            vo.setPersonGroup(pList);
            List<MyArticleDetailVO.Item> dList = contactGroupList(healthInfo.getDiseaseGroupList(), healthInfo.getDiseaseGroupName());
            vo.setDiseaseGroup(dList);

            return vo;
        }
        return null;
    }

    private List<MyArticleDetailVO.Item> contactGroupList(String idList, String nameList) {
        List<MyArticleDetailVO.Item> tempList = new ArrayList<>();
        if (CommonUtils.isNotEmpty(idList)) {
            String[] idArray = idList.split(",");
            String[] nameArray = new String[0];
            if (CommonUtils.isNotEmpty(nameList)) {
                nameArray = nameList.split(",");
            }
            for (int i = 0; i < idArray.length; i++) {
                MyArticleDetailVO.Item item = new MyArticleDetailVO.Item();
                item.setId(idArray[i]);
                item.setName(i > nameArray.length - 1 ? "" : nameArray[i]);
                tempList.add(item);
            }
        }
        return tempList;
    }

    /**
     * 客户端文章详情
     */
    @Override
    public ClientArticleDetailVO clientArticleDetail(String articleId) {
        HealthInfo healthInfo = healthInfoDAO.get(articleId);
        ClientArticleDetailVO vo = BeanUtils.copyProperties(healthInfo, ClientArticleDetailVO.class);
        if (CommonUtils.isEmpty(vo)) {
            return null;
        }
        // 附件列表
        String fileList = healthInfo.getFileList();
        if (CommonUtils.isNotEmpty(fileList)) {
            List<FileMetaEntity> userFileList = getUserFileList(Arrays.asList(fileList.split(",")));
            if (CommonUtils.isNotEmpty(userFileList)) {
                List<ClientArticleDetailVO.File> collect = userFileList.stream().map(file -> {
                    ClientArticleDetailVO.File f = new ClientArticleDetailVO.File();
                    f.setFileId(file.getFileId());
                    f.setFileName(file.getFileName());
                    return f;
                }).collect(Collectors.toList());
                vo.setFileList(collect);
            }
        }
        // 获取作者头像和作者职称
        String doctorId = healthInfo.getDoctorId();
        Doctor doctor = RpcUtil.invoke("hcn.doctor", "getById", doctorId);
        if (CommonUtils.isNotEmpty(doctor)) {
            vo.setAuthorAvatar(doctor.getAvatarFileId());
            //职级代码
            String level = doctor.getLevel();
            Dictionary dic = RpcUtil.invoke("hcn.doctor", "getDictionaryList");
            if (CommonUtils.isNotEmpty(dic)) {
                String text = dic.getText(level);
                vo.setAuthorTitle(text);
            }
        }
        //增加文章的阅读数
        HealthInfoInteractionCountUpdateDTO dto = new HealthInfoInteractionCountUpdateDTO();
        dto.setArticleId(articleId);
        dto.setReadCountAdd(1);
        healthInfoDAO.updateInteractionCount(dto);

        UserRoleToken current = UserRoleToken.getCurrent();
        if (null != current) {
            String userId = UserRoleToken.getCurrent().getUserId();
            if (CommonUtils.isNotEmpty(userId)) {
                //获取当前用户是否对当前文章点赞或者收藏
                BaseActionRecord likesAction = baseActionRecordService.getByBizKey(articleId, Constant.BUSINESS_TYPE, Constant.LIKES, userId);
                BaseActionRecord markAction = baseActionRecordService.getByBizKey(articleId, Constant.BUSINESS_TYPE, Constant.MARK, userId);

                vo.setLikes(CommonUtils.isNotEmpty(likesAction));
                vo.setCollection(CommonUtils.isNotEmpty(markAction));
            }
        }

        return vo;
    }

    /**
     * 新增,修改文章详情
     */
    @Override
    public void editArticle(EditArticleRequest request) throws ControllerException {
        String articleId = request.getArticleId();
        Date now = new Date();
        HealthInfo healthInfo = BeanUtils.copyProperties(request, HealthInfo.class);
        if (CommonUtils.isEmpty(healthInfo)) {
            throw new ControllerException("文章不能为空");
        }
        if (CommonUtils.isNotEmpty(request.getDiseaseGroup())) {
            List<EditArticleRequest.Item> diseaseGroup = request.getDiseaseGroup();
            List<String> idCollect = diseaseGroup.stream().map(EditArticleRequest.Item::getId).collect(Collectors.toList());
            List<String> nameCollect = diseaseGroup.stream().map(EditArticleRequest.Item::getName).collect(Collectors.toList());
            healthInfo.setDiseaseGroupList(String.join(",", idCollect));
            healthInfo.setDiseaseGroupName(String.join(",", nameCollect));
        }
        if (CommonUtils.isNotEmpty(request.getPersonGroup())) {
            List<EditArticleRequest.Item> personGroup = request.getPersonGroup();
            List<String> idCollect = personGroup.stream().map(EditArticleRequest.Item::getId).collect(Collectors.toList());
            List<String> nameCollect = personGroup.stream().map(EditArticleRequest.Item::getName).collect(Collectors.toList());
            healthInfo.setPersonGroupList(String.join(",", idCollect));
            healthInfo.setPersonGroupName(String.join(",", nameCollect));
        }
        if (CommonUtils.isNotEmpty(request.getFileList())) {
            healthInfo.setFileList(String.join(",", request.getFileList()));
        }

        //根据userid获取医生id
        UserRoleToken current = UserRoleToken.getCurrent();
        String userId = current.getUserId();
        DoctInfo doctInfo = RpcUtil.invoke("hcn.doctor", "getDocInfoByUserId", userId);
        if (CommonUtils.isNotEmpty(doctInfo)) {
            healthInfo.setDoctorId(doctInfo.getDoctorId());
        } else {
            throw new ControllerException("只有医护人员可以新增文章");
        }
        if (CommonUtils.isEmpty(articleId)) {

            healthInfo.setArticleId(UUID.randomUUID().toString());
            healthInfo.setAuthorId(userId);
            healthInfo.setAuthorName(current.getUserName());
            healthInfo.setGmtCreate(now);
            healthInfo.setGmtModified(now);
            healthInfo.setArticleStatus(ArticleStatusEnum.EDITED.getState());

            healthInfoDAO.insertSelective(healthInfo);
            HealthInfo healthInfoById = healthInfoDAO.getHealthInfoById(healthInfo.getArticleId());
            String tagCode = healthInfoById.getCategory();
            pcnTagsDAO.updateTagNumberAdd(tagCode);
        } else {
            healthInfo.setGmtModified(now);
            healthInfoDAO.updateSelective(healthInfo);
        }

    }

    /**
     * 提交健康资讯文章
     */
    @Override
    public void submitArticle(String articleId) {
        Optional<HealthInfoHandler> handler = getHandler(articleId);
        handler.ifPresent(HealthInfoHandler::submit);
    }

    private Optional<HealthInfoHandler> getHandler(String articleId) {
        HealthInfo healthInfo = healthInfoDAO.getHealthInfoById(articleId);
        HealthInfoHandler handler = null;
        if (CommonUtils.isNotEmpty(healthInfo)) {
            handler = new HealthInfoHandler(healthInfo.getArticleStatus(), healthInfo.getArticleId());
        }
        return Optional.ofNullable(handler);
    }

    /**
     * 撤回健康资讯文章
     */
    @Override
    public void withdrawArticle(String articleId) {
        Optional<HealthInfoHandler> handler = getHandler(articleId);
        handler.ifPresent(HealthInfoHandler::withdraw);
    }

    /**
     * 删除健康资讯文章
     */
    @Override
    public void deleteArticle(String articleId) {
        HealthInfo healthInfoById = healthInfoDAO.getHealthInfoById(articleId);
        healthInfoDAO.remove(articleId);
        String tagCode = healthInfoById.getCategory();
        pcnTagsDAO.updateTagNumberCut(tagCode);
    }

    /**
     * 管理员审核退回健康资讯文章
     */
    @Override
    public void rejectArticleByAdmin(String articleId) {
        Optional<HealthInfoHandler> handler = getHandler(articleId);
        handler.ifPresent(HealthInfoHandler::reject);
    }

    /**
     * 管理员发布健康资讯文章
     */
    @Override
    public void releaseArticle(String articleId) {
        Optional<HealthInfoHandler> handler = getHandler(articleId);
        handler.ifPresent(HealthInfoHandler::release);
    }

    /**
     * 管理员撤回健康资讯文章
     */
    @Override
    public void withdrawArticleByAdmin(String articleId) {
        Optional<HealthInfoHandler> handler = getHandler(articleId);
        handler.ifPresent(HealthInfoHandler::withdrawByAdmin);
    }

    /**
     * 健康资讯留言看板 只查看已发布的
     */
    @Override
    public List<CommentDashboardVO> commentDashboard(CommentDashboardRequest request) {
        Date now = new Date();
        Date start = null;
        Integer type = request.getType();
        if (Constant.THREE_MONTH.equals(type)) {
            start = DateUtils.caclDate(now, Calendar.MONTH, -3);

        } else if (Constant.ONE_YEAR.equals(type)) {
            start = DateUtils.caclDate(now, Calendar.MONTH, -12);
        }
        String userId = UserRoleToken.getCurrent().getUserId();
        HealthInfoCommentDashboardQo qo = new HealthInfoCommentDashboardQo();
        qo.setDateStart(start);
        qo.setAuthorId(userId);
        List<CommentDashboardVO> commentDashboard = healthInfoDAO.getCommentDashboard(qo);
        //  查询是否有新的留言
        if (CommonUtils.isNotEmpty(commentDashboard)) {
            List<String> articleIds = commentDashboard.stream().map(CommentDashboardVO::getArticleId).collect(Collectors.toList());
            List<String> newReply = healthInfoReplyDAO.findNewReply(articleIds);
            if (CommonUtils.isNotEmpty(newReply)) {
                Map<String, Boolean> newReplyMap = newReply.stream().collect(Collectors.toMap(r -> r, r -> Boolean.TRUE));
                commentDashboard.forEach(c -> c.setNewReply(newReplyMap.getOrDefault(c.getArticleId(), Boolean.FALSE)));
            }
        }
        return commentDashboard;
    }

    /**
     * 健康资讯留言看板列表 医生视图
     */
    @Override
    public SimplePageInfo<HealthInfoReplyListVO> commentList(CommentListRequest request) {
        String articleId = request.getArticleId();
        if (CommonUtils.isEmpty(articleId)) {
            return new SimplePageInfo<>();
        }
        SimplePageInfo<HealthInfoReplyListVO> rtn = getSpecialCommentList(request);
        //将留言设置为已读
        healthInfoReplyDAO.updateIsReadByArticleId(true, articleId);
        return rtn;
    }

    /**
     * 老的医生视图列表 备份
     *
     * @param request
     * @return
     */
    private SimplePageInfo<HealthInfoReplyListVO> oldCommentList(CommentListRequest request) {
        String articleId = request.getArticleId();
        HealthInfoReplyListQo qo = new HealthInfoReplyListQo();
        qo.setArticleId(articleId);
        qo.setPageSize(request.getPageSize());
        qo.setPageNo(request.getPageNo());
        qo.setFirst(true);
        qo.setDesc(true);
        SimplePageInfo<HealthInfoReplyBaseVO> page = healthInfoReplyDAO.getPageByParam(qo);
        if (CommonUtils.isEmpty(page) || CommonUtils.isEmpty(page.getList())) {
            return new SimplePageInfo<>();
        }
        List<HealthInfoReplyBaseVO> firstLevelReply = page.getList();

        HealthInfoReplyListQo qo2 = new HealthInfoReplyListQo();
        qo2.setArticleId(articleId);
        qo2.setSecond(true);

        List<HealthInfoReplyBaseVO> secondLevelReply = healthInfoReplyDAO.getListByParam(qo2);
        List<HealthInfoReplyListVO> list = alterCommentReplyList(firstLevelReply, secondLevelReply);
        SimplePageInfo<HealthInfoReplyListVO> rtn = new SimplePageInfo<>();
        rtn.setList(list);
        rtn.setTotal(page.getTotal());
        return rtn;
    }

    /**
     * 管理端医生页面获取某篇文章的留言列表 要求含有新回复留言的列表展示在最前
     */
    private SimplePageInfo<HealthInfoReplyListVO> getSpecialCommentList(CommentListRequest request) {
        String articleId = request.getArticleId();
        Integer pageNo = request.getPageNo();
        Integer pageSize = request.getPageSize();
        Integer offset = (pageNo - 1) * pageSize;
        //所有的一级留言
        HealthInfoReplyListQo l1 = new HealthInfoReplyListQo();
        l1.setArticleId(articleId);
        l1.setFirst(true);
        l1.setDesc(true);
        List<HealthInfoReplyBaseVO> firstLevelReply = healthInfoReplyDAO.getListByParam(l1);
        //所有的二级留言
        HealthInfoReplyListQo l2 = new HealthInfoReplyListQo();
        l2.setArticleId(articleId);
        l2.setSecond(true);
        l2.setDesc(true);
        List<HealthInfoReplyBaseVO> secondLevelReply = healthInfoReplyDAO.getListByParam(l2);
        //先组装后排序
        SimplePageInfo<HealthInfoReplyListVO> rtn = new SimplePageInfo<>();
        if (CommonUtils.isEmpty(firstLevelReply) && CommonUtils.isEmpty(secondLevelReply)) {
            return rtn;
        }
        String userId = UserRoleToken.getCurrent().getUserId();
        firstLevelReply.forEach(re -> {
            re.setAuthor(userId.equals(re.getReplyUserId()));
        });
        if (CommonUtils.isNotEmpty(secondLevelReply)) {
            secondLevelReply.forEach(re -> {
                re.setAuthor(userId.equals(re.getReplyUserId()));
            });
        }
        Long total = (long) firstLevelReply.size();
        rtn.setTotal(total);
        List<HealthInfoReplyListVO> middle = alterCommentReplyList(firstLevelReply, secondLevelReply);
        //排序规则 优先按照有新留言拍,然后按照回复时间排序
        List<HealthInfoReplyListVO> finalList = middle.stream().sorted((m1, m2) -> {
            Boolean m1Unread = !m1.getIsRead();
            Boolean m1SubUnread = CommonUtils.isNotEmpty(m1.getSubReplyList()) && m1.getSubReplyList().stream().anyMatch(m -> !m.getIsRead());
            Boolean m2Unread = !m2.getIsRead();
            Boolean m2SubUnread = CommonUtils.isNotEmpty(m2.getSubReplyList()) && m2.getSubReplyList().stream().anyMatch(m -> !m.getIsRead());

            Boolean m1U = m1Unread || m1SubUnread;
            Boolean m2U = m2Unread || m2SubUnread;

            if (m1U.equals(m2U)) {
                return 0;
            } else if (m1U) {
                return -1;
            } else {
                return 1;
            }
        }).skip(offset).limit(pageSize).collect(Collectors.toList());

        //╮(╯▽╰)╭ 对二级留言列表再排序 新留言优先
        finalList.stream().forEach(list -> {
            List<HealthInfoReplyListVO.SubReply> subReplyList = list.getSubReplyList();
            if (CommonUtils.isEmpty(subReplyList)) {
                return;
            }
            List<HealthInfoReplyListVO.SubReply> newSub = subReplyList.stream().sorted((m1, m2) -> {
                Boolean m1Read = m1.getIsRead();
                Boolean m2Read = m2.getIsRead();
                if (m1Read.equals(m2Read)) {
                    return 0;
                } else if (m1Read) {
                    return 1;
                } else {
                    return -1;
                }
            }).collect(Collectors.toList());
            list.setSubReplyList(newSub);
        });

        rtn.setList(finalList);
        return rtn;
    }

    private List<HealthInfoReplyListVO> alterCommentReplyList(List<HealthInfoReplyBaseVO> firstLevelReply,
                                                              List<HealthInfoReplyBaseVO> secondLevelReply) {
        List<HealthInfoReplyListVO> finalList;
        if (CommonUtils.isNotEmpty(secondLevelReply)) {
            //key 为 被上级留言id p_reply_id  value为回复某条留言的留言列表
            Map<Long, List<HealthInfoReplyBaseVO>> replyMap = secondLevelReply.stream()
                    .filter(r -> CommonUtils.isNotEmpty(r.getpReplyId()))
                    .filter(CommonUtils::isNotEmpty)
                    .collect(Collectors.toMap(HealthInfoReplyBaseVO::getpReplyId,
                            r -> Stream.of(r).collect(Collectors.toList()),
                            (v1, v2) -> {
                                //合并
                                v1.addAll(v2);
                                return v1;
                            }));
            finalList = firstLevelReply.stream().map(
                    r -> copyReplyVO(r, replyMap))
                    .collect(Collectors.toList());

        } else {
            finalList = firstLevelReply.stream().map(temp ->
                    BeanUtils.copyProperties(temp, HealthInfoReplyListVO.class)
            ).collect(Collectors.toList());
        }
        return finalList;
    }

    /**
     * 留言列表 端视图
     * 步骤 1.先查询出所有一级留言 降序
     * 步骤 2.查询出所有二级留言
     * 步骤 3.将二级留言按照时间升序拼接至一级留言中
     */
    @Override
    public List<HealthInfoReplyListVO> clientCommentList(String articleId) {
        if (CommonUtils.isEmpty(articleId)) {
            return Collections.emptyList();
        }
        HealthInfoReplyListQo qo = new HealthInfoReplyListQo();
        qo.setArticleId(articleId);
        qo.setFirst(true);
        qo.setDesc(true);
        List<HealthInfoReplyBaseVO> firstLevelReply = healthInfoReplyDAO.getListByParam(qo);
        if (CommonUtils.isEmpty(firstLevelReply)) {
            return Collections.emptyList();
        }

        HealthInfoReplyListQo qo2 = new HealthInfoReplyListQo();
        qo2.setArticleId(articleId);
        qo2.setSecond(true);

        List<HealthInfoReplyBaseVO> secondLevelReply = healthInfoReplyDAO.getListByParam(qo2);
        UserVo user = baseUserManageUnitService.getUserIdByOnline();
        String roleCd = user.getRoleId();
        //将留言设置为已读 todo 患者端和医生端是否要拆分为两个接口
        if (!RoleIdEnum.PATIENT.title().equals(roleCd)) {
            healthInfoReplyDAO.updateIsReadByArticleId(true, articleId);
        }

        return alterCommentReplyList(firstLevelReply, secondLevelReply);
    }

    /**
     * 对象复制转换
     */
    private HealthInfoReplyListVO copyReplyVO(HealthInfoReplyBaseVO r, Map<Long, List<HealthInfoReplyBaseVO>> replyMap) {
        Long replyId = r.getReplyId();
        HealthInfoReplyListVO vo = BeanUtils.copyProperties(r, HealthInfoReplyListVO.class);
        List<HealthInfoReplyBaseVO> baseVOS = replyMap.get(replyId);
        if (CommonUtils.isNotEmpty(baseVOS)) {
            List<HealthInfoReplyListVO.SubReply> subList = baseVOS.stream().map(b -> BeanUtils.copyProperties(b, HealthInfoReplyListVO.SubReply.class))
                    .collect(Collectors.toList());
            if (CommonUtils.isNotEmpty(vo)) {
                vo.setSubReplyList(subList);
            }
        }
        return vo;
    }

    /**
     * 健康资讯留言回复 开启事务
     */
    @Override
    @DAOTransaction
    public void replyMessage(CommentReplyRequest request) {
        Long targetReplyId = request.getTargetReplyId();
        Date now = new Date();
        HealthInfoReply reply = new HealthInfoReply();
        reply.setArticleId(request.getArticleId());
        reply.setpReplyId(request.getpReplyId());
        reply.setTargetReplyId(targetReplyId);
        reply.setReplyTime(now);
        reply.setReplyContent(request.getReplyContent());

        UserRoleToken current = UserRoleToken.getCurrent();
        String roleId = RoleUtils.getCurrentCommonRole();
        String userId = current.getUserId();
        reply.setReplyUserRole(roleId);
        reply.setReplyUserId(userId);
        reply.setReplyUserName(current.getUserName());

        if (CommonUtils.isNotEmpty(targetReplyId)) {
            //targetReplyId  查询原留言数据
            HealthInfoReply targetReply = healthInfoReplyDAO.get(targetReplyId);
            if (CommonUtils.isNotEmpty(targetReply)) {
                reply.setTargetUserId(targetReply.getReplyUserId());
                reply.setTargetUserName(targetReply.getReplyUserName());
                reply.setTargetUserRole(targetReply.getReplyUserRole());
            }
        }
        reply.setGmtCreate(now);
        reply.setGmtModified(now);

        //非用户留言 判断是否是给自己的文章留言
        if (CommonUtils.isNotEmpty(userId) && !UserRoleEnum.PATIENT.getTitle().equals(roleId)) {
            HealthInfo healthInfo = healthInfoDAO.getHealthInfoById(request.getArticleId());
            if (CommonUtils.isNotEmpty(healthInfo) && userId.equals(healthInfo.getAuthorId())) {
                reply.setIsRead(Boolean.TRUE);
            }
        }
        healthInfoReplyDAO.insertSelective(reply);

        //增加文章的评论数
        HealthInfoInteractionCountUpdateDTO dto = new HealthInfoInteractionCountUpdateDTO();
        dto.setArticleId(request.getArticleId());
        dto.setCommentCountAdd(1);
        healthInfoDAO.updateInteractionCount(dto);


    }

    /**
     * 点赞\分享\收藏 等互动操作
     */
    @Override
    @DAOTransaction
    public void interaction(ArticleInteractionRequest request) {
        String articleId = request.getArticleId();
        HealthInfoInteractionCountUpdateDTO dto = new HealthInfoInteractionCountUpdateDTO();
        dto.setArticleId(articleId);
        String action = request.getAction();
        CmsActionEnum byName = CmsActionEnum.getByName(action);
        if (CommonUtils.isEmpty(byName)) {
            throw new ServiceException("不支持的操作类型");
        }
        String userId = UserRoleToken.getCurrent().getUserId();
        BaseActionRecord byBizKey = null;
        if (CommonUtils.isNotEmpty(request.getBusinessType())) {
            byBizKey = baseActionRecordService.getByBizKey(articleId, request.getBusinessType(), action, userId);
        } else {
            byBizKey = baseActionRecordService.getByBizKey(articleId, Constant.BUSINESS_TYPE, action, userId);
        }


        // 互动操作记录数据库
        if (request.isCancel()) {
            //删除操作记录
            if (CommonUtils.isEmpty(byBizKey)) {
                return;
            }
            if (CommonUtils.isNotEmpty(request.getBusinessType())) {
                baseActionRecordService.removeAction(articleId, request.getBusinessType(), action, userId);
            } else {
                baseActionRecordService.removeAction(articleId, Constant.BUSINESS_TYPE, action, userId);
            }
        } else {
            //新增前查询是否存在?
            if (CommonUtils.isNotEmpty(byBizKey) && !CmsActionEnum.share.name().equals(action)) {
                return;
            }
            BaseActionRecord record = new BaseActionRecord();
            record.setAction(action);
            if (CommonUtils.isEmpty(request.getBusinessType())) {
                record.setBusinessType(BusinessTypeEnum.news.name());
            } else {
                record.setBusinessType(request.getBusinessType());
            }
            record.setBusinessId(articleId);
            record.setUserId(userId);
            record.setGmtCreate(new Date());
            baseActionRecordService.saveAction(record);
        }
        //把点赞、分享、收藏动作发送至MQ消息，让消费者处理
        sendInteractionService.productionMessage(request);
    }

    /**
     * 获取用户收藏的健康资讯列表
     */
    @Override
    public SimplePageInfo<MyArticleListVO> getMarkedHealthInfo(PageQo qo) {
        String userId = UserRoleToken.getCurrent().getUserId();
        List<String> articleIds = baseActionRecordService.getBusinessIdList(Constant.BUSINESS_TYPE, Constant.MARK, userId);
        if (CommonUtils.isEmpty(articleIds)) {
            return new SimplePageInfo<>();
        }
        MyArticleListQo articleListQo = new MyArticleListQo();
        articleListQo.setArticleIds(articleIds);
        articleListQo.setPageNo(qo.getPageNo());
        articleListQo.setPageSize(qo.getPageSize());
        SimplePageInfo<HealthInfo> healthInfoPage = healthInfoDAO.getHealthInfoPage(articleListQo);
        return alterArticleList(healthInfoPage);
    }


    /**
     * @Author:FangZhiYi
     * @Description 妇幼资讯获取所有资讯列表
     * @Params [request]
     * @Return org.atag.dao.model.SimplePageInfo<hcn.base.healthinfo.vo.MyArticleListVO>
     * @Data Created in 2022/7/18 11:19
     * @Moddified By:
     */
    @Override
    public SimplePageInfo<MyArticleListVO> queryArticleListForClass(MyArticleListRequest request) {
        MyArticleListQo qo = copyArticleListQo(request);
        qo.setUserId(null);
        if (0 == request.getArticleStatus()) {
            qo.setArticleStatus(null);
        } else {
            qo.setArticleStatus(request.getArticleStatus());
        }
        qo.setDesc(true);
        qo.setTitle(request.getTitle());
        qo.setPageSize(request.getPageSize());
        SimplePageInfo<HealthInfo> healthInfoList = healthInfoDAO.getHealthInfoPage(qo);
        return alterArticleList(healthInfoList);
    }

    /**
     * @Author:FangZhiYi
     * @Description 查询文章列表阅读量
     * @Params [articleIdArr]
     * @Return java.lang.Long
     * @Data Created in 2022/7/18 16:25
     * @Moddified By:
     */
    @Override
    @RpcService
    public Long getReadingVolumeForInfo(String articleIds) {
        String[] articleIdArr = articleIds.split(",");
        List<String> articleIdList = Arrays.asList(articleIdArr);
        long count = healthInfoDAO.getReadingVolumeForInfo(articleIdList);
        return count;
    }


    /**
     * @Author:FangZhiYi
     * @Description 根据文章ID数组查询文章列表
     * @Params [articleIdArr]
     * @Return org.atag.dao.model.SimplePageInfo<hcn.base.healthinfo.vo.MyArticleListVO>
     * @Data Created in 2022/7/20 11:39
     * @Moddified By:
     */
    @Override
    @RpcService
    public SimplePageInfo<MyArticleListVO> queryWoAndChInfoClassArticleList(String articleIds, String title, Integer status) {
        MyArticleListQo qo = new MyArticleListQo();
        qo.setUserId(null);
        if (status == 0) {
            qo.setArticleStatus(null);
        } else {
            qo.setArticleStatus(status);
        }
        qo.setTitle(title);
        String[] articleIdArr = articleIds.split(",");
        List<String> articleIdList = Arrays.asList(articleIdArr);
        qo.setArticleIds(articleIdList);
        qo.setDesc(true);
        SimplePageInfo<HealthInfo> healthInfoList = healthInfoDAO.getHealthInfoPage(qo);
        return alterArticleList(healthInfoList);
    }


    @Override
    public SimplePageInfo<NewReplyListVO> getNewReplyList(PageQo qo) {
        //查询当前医生未读的留言列表  未读的  一级的  或者  被回复的
        String userId = UserRoleToken.getCurrent().getUserId();

        NewReplyListQo replyListQo = new NewReplyListQo();
        replyListQo.setUserId(userId);
        replyListQo.setPageNo(qo.getPageNo());
        replyListQo.setPageSize(qo.getPageSize());
        SimplePageInfo<NewReplyListVO> newReplyList = healthInfoReplyDAO.getNewReplyList(replyListQo);

        List<NewReplyListVO> list = newReplyList.getList();
        //查找文章标题
        if (CommonUtils.isNotEmpty(list)) {
            List<String> articleIdList = list.stream().map(NewReplyListVO::getArticleId).distinct().collect(Collectors.toList());
            List<HealthInfo> infoList = healthInfoDAO.findHealthInfoListByIds(articleIdList);
            if (CommonUtils.isNotEmpty(infoList)) {
                Map<String, String> titleMap = infoList.stream().collect(Collectors.toMap(HealthInfo::getArticleId, HealthInfo::getTitle));
                list.forEach(info -> info.setTitle(titleMap.get(info.getArticleId())));
            }
        }

        return newReplyList;
    }

    /**
     * 获取首页新留言数量
     *
     * @param  userId
     * @return * @return : java.lang.Long
     * @author Qulc - 2023/10/25 17:18
     */
    @RpcService
    @Override
    public NumberMessagesVO getNewReplNum(String userId) {
        String useId = UserRoleToken.getCurrent().getUserId();
        NumberMessagesVO numberMessagesVO = new NumberMessagesVO();
        NewReplyListQo replyListQo = new NewReplyListQo();
        replyListQo.setUserId(useId);
        SimplePageInfo<NewReplyListVO> newReplyList = healthInfoService.getNewReplyList(replyListQo);
        numberMessagesVO.setTotal(newReplyList.getTotal());
        return numberMessagesVO;
    }


    /**
     * 更新资讯评价已读
     *
     * @param replyId
     */
    @Override
    public void readNewReply(Long replyId) throws ControllerException {
        HealthInfoReply healthInfoReply = healthInfoReplyDAO.get(replyId);
        if (healthInfoReply != null && !healthInfoReply.getIsRead()) {
            healthInfoReply.setIsRead(true);
            healthInfoReply.setGmtRead(new Date());
            healthInfoReplyDAO.update(healthInfoReply);
        }
    }

    @Override
    public List<String> getCanDoOrNotInfo(PageQo qo) {
        String userId = UserRoleToken.getCurrent().getUserId();
        List<String> doList = baseActionRecordService.getBusinessIdList(Constant.DO, Constant.MARK, userId);
        if (CommonUtils.isEmpty(doList)) {
            return null;
        }
        return doList;
    }

    @Override
    public List<String> getCanEatOrNotInfo(PageQo qo) {
        String userId = UserRoleToken.getCurrent().getUserId();
        List<String> eatList = baseActionRecordService.getBusinessIdList(Constant.EAT, Constant.MARK, userId);
        if (CommonUtils.isEmpty(eatList)) {
            return null;
        }
        return eatList;
    }

    public interface Constant {
        Integer ALL = 0;
        Integer THREE_MONTH = 2;
        Integer ONE_YEAR = 1;
        Integer RECOMMEND_TYPE = 0;

        String BUSINESS_TYPE = "news";
        String MARK = "mark";
        String LIKES = "likes";
        //do-能不能做,eat-能不能吃
        String DO = "do";
        String EAT = "eat";
    }

    /**
     * @param qo
     * @return org.atag.dao.model.SimplePageInfo<pcn.bean.FindPatientLeaveMessageVo>
     * @description:查询健康咨询评论列表
     * @author: zsf
     * @date: 2023/8/1 0001 16:55
     */
    @Override
    public SimplePageInfo<FindPatientLeaveMessageVo> findPatientLeaveMessage(FindPatientLeaveMessageQo qo) throws ControllerException {
        //框架自带-也可以通过表查询到当前登录用户的userid
        String userId = UserRoleToken.getCurrent().getUserId();
        if (CommonUtils.isNotEmpty(userId)) {
            qo.setReplyUserId(userId);
        } else {
            return null;
        }
        SimplePageInfo<FindPatientLeaveMessageVo> vo = healthInfoReplyDAO.getReplyListActionByParam(qo, true);
        return vo;
    }

    /**
     * @param qo
     * @return void
     * @description: 更新留言已读未读状态
     * @author: zsf
     * @date: 2023/8/2 0002 17:43
     */
    @Override
    public void updatePatientLeaveMessage(HealthInfoReply qo) throws ControllerException {
        healthInfoReplyDAO.updatePatientLeaveMessage(qo.getReplyId());
    }

    /**
     * 获取指定时间医生发资讯量
     *
     * @param doctorIds
     * @return
     */
    @Override
    public long getCountByDoctorIds(List<String> doctorIds) throws ControllerException {
        return healthInfoReplyDAO.getCountByDoctorIds(doctorIds);
    }
}
